<template>
    <el-dialog
        v-model="dialogVisible"
        custom-class="label-dialog-box"
        :title="title"
        width="1000px"
        :append-to-body="true"
        :before-close="cancelHandel">
        <div class="el-dialog-body">
            <section class="dialog-content-box">
                <div class="seach">
                    <el-row>
                        <el-col :span="hasConditiion ? 24 : 14">
                            <el-input
                                v-model="dialogData.seachKey"
                                v-debounce="[seachTab]"
                                placeholder="搜索标签组、标签"
                                :prefix-icon="Search" />
                        </el-col>
                        <el-col v-show="!hasConditiion" :span="10" style="text-align: right">
                            <div class="refresh" @click="doRefreshTag">
                                <el-icon class="icon"><refresh-right /></el-icon><span>刷新数据</span>
                            </div>
                            <span>标签不存在？</span>
                            <span class="active" @click="toCreate">
                                <span class="fa fa-edit link-btn" @click="toCreatedLink('')">去创建</span>
                            </span>
                        </el-col>
                    </el-row>
                </div>
                <template v-if="labelList.length > 0">
                    <div class="dialog-title">
                        <div>
                            <div class="tag-group">标签组类别</div>
                            <div class="total-group">
                                <el-scrollbar height="381px">
                                    <div
                                        v-for="item in labelList"
                                        :key="item.id"
                                        :class="item.isSelected ? 'group-tag tag-color' : 'group-tag'"
                                        @click="handleClick(item)">
                                        <el-tooltip
                                            placement="top"
                                            trigger="hover"
                                            :disabled="!item.isShowTooltip"
                                            effect="dark"
                                            :content="item.name">
                                            {{ item.name }}
                                        </el-tooltip>
                                    </div>
                                </el-scrollbar>
                            </div>
                        </div>
                        <div>
                            <div class="tag-group tag-list">标签组/标签</div>
                            <div class="label-list-content">
                                <el-scrollbar v-if="itemValue?.list?.length > 0" height="349px">
                                    <div v-for="itm in itemValue.list" :key="itm.group_id" class="label-list">
                                        <div class="title">{{ itm.group_name }}</div>
                                        <div class="label-item-box">
                                            <div
                                                v-for="(it, ind) in itm.tags"
                                                :key="ind"
                                                :class="{ active: hasChooseDataArr(it) }"
                                                @click="chooseTag(it)">
                                                {{ it.name }}
                                            </div>
                                        </div>
                                    </div>
                                </el-scrollbar>
                                <div v-else height="400px">
                                    <el-empty :image="noDataImgUlr" description="暂无数据"></el-empty>
                                </div>
                            </div>
                        </div>
                    </div>
                </template>
                <div v-else height="400px">
                    <el-empty :image="noDataImgUlr" description="暂无数据"></el-empty>
                </div>
            </section>

            <div class="dialog-content-right">
                <div class="right-title">
                    <div>
                        <span>已选标签</span>
                        <span class="span">（{{ chooseArr.length }}个）</span>
                    </div>
                    <div><span class="active" @click="clearChoose">清空</span></div>
                </div>

                <div class="choose-tag">
                    <span v-for="tag in chooseArr" :key="tag">
                        <el-tooltip
                            effect="dark"
                            placement="top"
                            popper-class="tool-tip"
                            :disabled="!tag.group_name"
                            :content="`${tag.group_name}/${tag.name}`">
                            <el-tag type="info" style="margin: 0 5px 5px 0" closable @close="onClose(tag)">
                                {{ tag.name }}
                            </el-tag>
                        </el-tooltip>
                    </span>
                </div>
            </div>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <div>
                    <el-button @click="cancelHandel">取消</el-button>
                    <el-button type="primary" @click="submitHandel">保存</el-button>
                </div>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { nextTick, ref, watch, onMounted, getCurrentInstance, computed } from 'vue';
import {
    ElButton,
    ElTag,
    ElDialog,
    ElIcon,
    ElRow,
    ElCol,
    ElInput,
    ElTooltip,
    ElEmpty,
    ElScrollbar
} from 'element-plus';
import { Search, RefreshRight } from '@element-plus/icons-vue';
import { getSetionId, IsNotEmpty } from '../utils/index';
import {
    getCustTagsTypes,
    getCustGroupTagsTypes,
    getCustTagsList,
    getCustGroupTagsList,
    queryCustTagsList,
    queryCustGroupTagsList
} from '../api/selectCustTag';
import { ILabelChoseType, ILabelType } from './type';
import { vDebounce } from '../utils/directives';

defineOptions({
    name: 'ZwUnityKitSelectCustTags'
});

const dialogData = ref<{ seachKey: string; activeName: number }>({
    seachKey: '',
    activeName: 1 //当前标签页
});
const labelList = ref<Array<any>>([]);
const chooseArr = ref<Array<any>>([]); //当前选中的标签
let pageParam = { page: 1, page_size: 100 };
let canScroll = true;
let isCreate = false; //当前是否前往创建标签页面了
const itemValue = ref(); //选中的标签组下的标签数据
const noDataImgUlr = ref('https://img.static-keyid.cn/toolspace/scrm/2023/09/1693896897997xzkiue88svwijh0d.png');
const app = getCurrentInstance();

// 数据加载完的id
const loadEndIds: number[] = [];

interface PropsType {
    title: string; // 弹框标题
    type: boolean; // true：数据源为客户标签；false：数据源是客户群标签
    labelChooseType: ILabelChoseType; // 1是批量打标签   2 是选择标签
    labelType: ILabelType; // 0 无标签 1 满足任意一个标签  2 同时满足所有标签  3 批量打标签  4 删除
    hasConditiion: boolean; // 是否有搜索栏上面的功能 true 没有刷新创建功能  false 有刷新创建功能
    modelValue: boolean; // 是否显示组件
    chooseDataArr: Array<any>; // 回显的标签数据  {id:***,name:***}
}

const props = withDefaults(defineProps<PropsType>(), {
    title: '选择标签',
    type: true,
    labelChooseType: 1,
    labelType: 3,
    hasConditiion: true,
    modelValue: false,
    chooseDataArr: () => []
});

const emit = defineEmits(['update:modelValue', 'submit', 'close']);

const dialogVisible = computed({
    set(val) {
        emit('update:modelValue', val);
    },
    get() {
        return props.modelValue;
    }
});

const initDataFun = () => {
    dialogData.value = {
        seachKey: '',
        activeName: 1 //当前标签页
    };
};

// 移除标签
const onClose = tag => {
    tag.check = !tag.check;
    chooseArr.value = chooseArr.value.filter(item => item.id != tag.id);
};

// 获取标签组类别列表
const getListGroupType = () => {
    if (props.type) {
        return getCustTagsTypes(app);
    } else {
        return getCustGroupTagsTypes(app);
    }
};

watch(
    () => props.modelValue,
    async val => {
        if (val) {
            if (props.chooseDataArr.length) {
                chooseArr.value.push(...props.chooseDataArr);
            }
            isCreate = false; //初始化
            pageParam = {
                page: 1,
                page_size: 100
            };
            loadEndIds.length = 0; // 清空数据已经加载完的的id
            initDataFun();
            const groupData = await getListGroupType();
            labelList.value = groupData && groupData.length > 0 ? groupData : [];
            dialogData.value.activeName = labelList.value.length > 0 ? labelList.value[0].id : '';
            itemValue.value = labelList.value.length > 0 ? labelList.value[0] : '';
            labelList.value.map(item => {
                item.isSelected = false;
                item.isShowTooltip = item.name.toString().pxWidth('normal 14px sans-serif') > 122;
            });
            labelList.value[0].isSelected = true;
            getListTagFun();
        }
    }
);

//设置标签组类别hover显示
(String as any).prototype.pxWidth = function (font) {
    const canvas =
        (String as any).prototype.pxWidth.canvas ||
        ((String as any).prototype.pxWidth.canvas = document.createElement('canvas'));
    const context = canvas.getContext('2d');
    font && (context.font = font);
    const metrics = context.measureText(this);
    return metrics.width;
};

/**
 * 是否在选中的里面存在这一条
 */
const hasChooseDataArr = tag => {
    return chooseArr.value.some(item => item.id == tag.id);
};

/**
 * 刷新数据
 */
const doRefreshTag = () => {
    pageParam = {
        page: 1,
        page_size: 100
    };
    // 清空当前列表
    const currentList = labelList.value.find(it => {
        return it.id == dialogData.value?.activeName;
    });
    if (currentList) {
        currentList.list?.splice?.(0);
    }
    getListTagFun();
};

// 获取标签组内的数据
const getListTagFun = () => {
    const index = labelList.value.findIndex(it => {
        return it.id == dialogData.value?.activeName;
    });
    if (!labelList.value[index].list) {
        itemValue.value.list = [];
    }
    if (!dialogData.value?.activeName) {
        return;
    }
    if (props.type) {
        const data = {
            keyword: dialogData.value?.seachKey,
            type_list: dialogData.value?.activeName,
            page: pageParam.page,
            page_size: pageParam.page_size
        };
        getCustTagsList(app, data)
            .then(r => {
                r.data.forEach(item => {
                    item.tags.forEach(itm => {
                        const indx = chooseArr.value.findIndex(it => {
                            return it.id == itm.id;
                        });
                        if (indx > -1) {
                            itm.check = true;
                        }
                        itm.group_name = item.group_name;
                    });
                });
                // 如果没标签，则当作数据已经加载完毕
                if (!r.data.length) {
                    loadEndIds.push(dialogData.value?.activeName);
                }
                itemValue.value.list = r.data;
                nextTick(() => {
                    canScroll = true;
                });
            })
            .catch(e => {
                canScroll = true;
            });
    } else {
        const data = {
            keyword: dialogData.value?.seachKey,
            type_list: [dialogData.value?.activeName],
            page: pageParam.page,
            page_size: pageParam.page_size
        };
        getCustGroupTagsList(app, data)
            .then(r => {
                r.data.forEach(item => {
                    item.tags.forEach(itm => {
                        const indx = chooseArr.value.findIndex(it => {
                            return it.id == itm.id;
                        });
                        if (indx > -1) {
                            itm.check = true;
                        }
                        itm.group_name = item.group_name;
                    });
                });
                itemValue.value.list = r.data;
                nextTick(() => {
                    canScroll = true;
                });
            })
            .catch(e => {
                canScroll = true;
            });
    }
};

const cancelHandel = () => {
    clearChoose();
    dialogVisible.value = false;
    emit('close');
};

// 前往创建
const toCreate = () => {
    isCreate = true;
};

// 滚动加载
const pageScroll = e => {
    const scrollView: any = document.querySelector('.label-list-content .el-scrollbar__view');
    // 如果该条数据已经加载完毕，则不再加载其他数据
    if (loadEndIds.includes(dialogData.value?.activeName)) {
        return;
    }
    if (e.scrollTop >= scrollView?.clientHeight - 270 && canScroll) {
        canScroll = false;
        pageParam.page = pageParam.page + 1;
        getListTagFun();
    }
};

// 保存数据
const submitHandel = () => {
    const { labelChooseType, labelType } = props;
    const arr = [...chooseArr.value];
    const idList = arr.map(it => {
        return it.id;
    });
    if (labelType != 0) {
        emit('submit', { labelChooseType, labelType, data: arr, idList });
    } else {
        emit('submit', { labelChooseType, labelType, data: [], idList: [] });
    }
    cancelHandel();
};

// 选择选项卡
const handleClick = val => {
    labelList.value.map(item => {
        if (item.id == val.id) {
            item.isSelected = true;
        } else {
            item.isSelected = false;
        }
    });
    dialogData.value.activeName = val.id;
    pageParam = {
        page: 1,
        page_size: 100
    };
    getListTagFun();
};

// 选择标签
const chooseTag = val => {
    const index = chooseArr.value.findIndex(it => {
        return it?.id == val?.id;
    });
    if (index > -1) {
        chooseArr.value.splice(index, 1);
    } else {
        chooseArr.value.push(val);
    }
};

// 清空选中的标签
const clearChoose = () => {
    chooseArr.value.splice(0);
    const keyArr = Object.keys(labelList.value);
    keyArr.forEach(item => {
        if (labelList.value[item].list) {
            labelList.value[item].list.forEach(itm => {
                if (itm.tags && itm.tags.length > 0) {
                    itm.tags.forEach(it => {
                        it.check = false;
                    });
                }
            });
        }
    });
    // 点击右侧清除同时也清空筛选项
    dialogData.value.seachKey = '';
    pageParam = {
        page: 1,
        page_size: 100
    };
    // seachTab();
};

const seachTab = async () => {
    const params = { keyword: dialogData.value?.seachKey };
    try {
        const res = props.type ? await queryCustTagsList(app, params) : await queryCustGroupTagsList(app, params);
        const arr: any[] = [];
        res.forEach(item => {
            item.list = props.type ? item.tag_groups : item.group_chat_tag_groups;
            if (IsNotEmpty(item.list)) {
                item.list.forEach(v => {
                    v.group_id = v.type_id;
                    v.group_name = v.name;
                    v.tags = props.type ? v.cust_tag : v.cust_group_tag;
                    v.tags.forEach(it => {
                        it.group_name = v.group_name;
                    });
                });
            }
            arr.push(item);
        });
        if (arr.length) dialogData.value.activeName = arr[0].id;
        getSelectLabel(arr); // 回显选中数据
        labelList.value = arr;
        labelList.value.map(item => {
            item.isShowTooltip = item.name.toString().pxWidth('normal 14px sans-serif') > 122;
        });
        itemValue.value = labelList.value.length > 0 ? labelList.value[0] : '';
        labelList.value[0].isSelected = true;
    } catch (error) {}
};

// 选中回显
const getSelectLabel = data => {
    if (chooseArr.value.length > 0) {
        const arr: any[] = getSetionId('id', chooseArr.value);
        data.forEach(item => {
            if (item.list.length > 0) {
                item.list.forEach(v => {
                    if (v?.cust_tag.length > 0) {
                        v?.cust_tag.forEach(k => {
                            if (arr.includes(k?.id)) {
                                k.check = true;
                            }
                        });
                    }
                });
            }
        });
    }
};

const toCreatedLink = url => {
    window.open(url || '/customer/tag/manage', '_blank');
};

const onOpen = () => {
    dialogVisible.value = true;
};

onMounted(() => {
    document.addEventListener('visibilitychange', function () {
        //浏览器切换事件
        if (document.visibilityState != 'hidden' && isCreate) {
            getListTagFun();
            isCreate = false;
        }
    });
});

defineExpose({
    onOpen,
    dialogData,
    clearChoose
});
</script>

<style lang="scss" scoped>
@import './Index';
</style>
